package com.foryou.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foryou.wechat.common.Constants;
import com.foryou.wechat.common.enums.CapacityEnum;
import com.foryou.wechat.entity.UserEntity;
import com.foryou.wechat.entity.UserFollowEntity;
import com.foryou.wechat.mapper.UserFollowMapper;
import com.foryou.wechat.mapper.UserMapper;
import com.foryou.wechat.model.vo.FollowVo;
import com.foryou.wechat.model.vo.UserVo;
import com.foryou.wechat.service.UserFollowService;
import com.foryou.wechat.utils.EnumUtil;
import com.foryou.wechat.utils.HttpContextUtils;
import com.foryou.wechat.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Lee.
 */
@Service
public class UserFollowServiceImpl implements UserFollowService {

    private final UserFollowMapper userFollowMapper;

    private final UserMapper userMapper;

    public UserFollowServiceImpl(UserFollowMapper userFollowMapper, UserMapper userMapper) {
        this.userFollowMapper = userFollowMapper;
        this.userMapper = userMapper;
    }

    @Override
    public int followUserList(Long userId) {
        return userFollowMapper.selectCount(new QueryWrapper<UserFollowEntity>()
                .eq("from_user_id", userId));
    }

    @Override
    public int fansUserList(Long userId) {
        return userFollowMapper.selectCount(new QueryWrapper<UserFollowEntity>()
                .eq("to_user_id", userId));
    }

    @Override
    public Response getFollowUserList(int start,Long userId) {
        List<UserFollowEntity> followUserList = userFollowMapper.getFollowUserList(start,userId);
        return Response.success(dataAssemble(followUserList));
    }

    @Override
    public Response getFansUserList(int start,Long userId) {
        List<UserFollowEntity> followUserList = userFollowMapper.getFansUserList(start,userId);
        return Response.success(dataAssemble(followUserList));
    }

    @Override
    @Transactional
    public Response followUser(Long userId) {

        //1.从session 获取 userId信息 TODO
        Long sessionUserId = HttpContextUtils.getUserId();
        if (userId.equals(sessionUserId)) {
            return Response.failure("不能自己关注自己哦~");
        }
        //2.检测该用户是否也关注了自己
        UserFollowEntity followEntity = userFollowMapper.selectOne(
                new QueryWrapper<UserFollowEntity>()
                        .eq("from_user_id", userId)
                        .eq("to_user_id",sessionUserId)
        );

        UserFollowEntity newUserFollowEntity = new UserFollowEntity(sessionUserId,userId, Constants.USER_NO);
        //3.如果关注了自己修改两条记录的状态为互粉
        if (!ObjectUtils.isEmpty(followEntity)) {
            followEntity.setBothStatus(Constants.USER_YES);
            newUserFollowEntity.setBothStatus(Constants.USER_YES);
            userFollowMapper.updateById(followEntity);
        }
        int insert = userFollowMapper.insert(newUserFollowEntity);
        return insert > 0 ? Response.success() : Response.failure(Constants.OPERATION_FAILURE);
    }

    @Override
    @Transactional
    public void cancelUser(Long userId) {

        //1.从session 获取 userId信息 TODO
        Long sessionUserId = HttpContextUtils.getUserId();

        //2.查询该取消关注用户是否已经关注了自己
        UserFollowEntity followEntity = userFollowMapper.selectOne(
                new QueryWrapper<UserFollowEntity>()
                        .eq("from_user_id", userId)
                        .eq("to_user_id",sessionUserId)
        );

        //3.如果取消关注用户关注了自己 修改记录的状态为单一关注
        if (!ObjectUtils.isEmpty(followEntity) && followEntity.getBothStatus().equals(Constants.USER_YES)) {
            followEntity.setBothStatus(Constants.USER_NO);
            userFollowMapper.updateById(followEntity);
        }

        //4.取消关注 删除记录
        int result = userFollowMapper.delete(new QueryWrapper<UserFollowEntity>()
                .eq("from_user_id", sessionUserId)
                .eq("to_user_id", userId));

        if (result < 0) {
            throw new RuntimeException("系统异常");
        }
    }

    /**
     * 组装数据
     * @param followUserList
     * @return
     */
    private List<FollowVo> dataAssemble(List<UserFollowEntity> followUserList) {
        List<FollowVo> fansVoList = new ArrayList<>();

        followUserList.forEach(e->{
            fansVoList.add(new FollowVo(
                    e.getUserEntity().getId(),
                    e.getUserEntity().getNickname(),
                    e.getUserEntity().getAvatarUrl(),
                    EnumUtil.getEnumByCode(CapacityEnum.class,e.getUserEntity().getCapacity()),
                    e.getUserEntity().getProvince(),
                    Constants.USER_YES.equals(e.getBothStatus())
            ));
        });

        return fansVoList;
    }

    @Override
    public boolean isFollow(Long userId) {

        //从session获取用户Id
        Long sessionUserId = HttpContextUtils.getUserId();
        UserFollowEntity userFollowEntity = userFollowMapper.selectOne(new QueryWrapper<UserFollowEntity>()
                .eq("from_user_id", sessionUserId)
                .eq("to_user_id", userId)
        );
        return !ObjectUtils.isEmpty(userFollowEntity);
    }

    @Override
    public UserVo getUserVo(Long userId) {
        //从session获取用户Id
        Long sessionUserId = HttpContextUtils.getUserId();
        UserEntity userEntity = userMapper.selectById(userId);
        if (ObjectUtils.isEmpty(userEntity)) {
            return new UserVo();
        }
        //组装用户信息
        UserVo userVo = new UserVo(
                userEntity.getId(),
                userEntity.getNickname(),
                EnumUtil.getEnumByCode(CapacityEnum.class,userEntity.getCapacity()),
                userEntity.getGender(),
                userEntity.getAvatarUrl(),
                false
        );
        //如果查询的用户不是本身
        if (!userId.equals(sessionUserId)) {
            //4.查询是否关注该用户
            userVo.setFollow(this.isFollow(userId));
        }
        return userVo;
    }

}
